<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/10/30
 * Time: 5:53 PM
 */

namespace app\aliyun\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\lib\AliOss;
use think\Env;
use think\Log;

class AliyunVoice
{
    protected static $accessId = 'LTAI5tHqG8V5i3vJzBuCeJxV';
    protected static $accessSecret = 'YS0eKv9SWsa6u4RBs3GQ0Y0PwpvtdC';

    /**
     * 提交语音检测
     * @param $url
     * @return mixed|string
     * @throws ClientException
     */
    public static function submitVoice($url)
    {
        if (!$url)
        {
            return '';
        }
        AlibabaCloud::accessKeyClient(self::$accessId, self::$accessSecret)
            ->regionId('cn-shanghai')
            ->asDefaultClient()->options([

            ]);
        $taskId = '';
        //获取RTC的录音
        $aliOss = AliOss::getInstance()->setConfig('rtc');
        $host = Env::get('host.name');
        $url = strstr($url, 'rtc/' . $host);
        $url = $url ? $aliOss->getAuth($url) : '';
        try
        {
            $result = AlibabaCloud::rpc()
                ->product('Green')
                // ->scheme('https') // https | http
                ->version('2022-03-02')
                ->action('VoiceModeration')
                ->method('POST')
                ->host('green-cip.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'Service' => "audio_media_detection",
                        'ServiceParameters' => json_encode([
                            'Url' => $url
                        ])
                    ],
                ])
                ->request();
            $res = $result->toArray();
            if ($res['Code'] === 200)
            {
                $taskId = $res['Data']['TaskId'];
            } else
            {
                Log::write($res['Message'], 'error', true);
            }
        }
        catch (ClientException $e)
        {
            Log::write($e->getErrorMessage(), 'error', true);
        }
        catch (ServerException $e)
        {
            Log::write($e->getErrorMessage(), 'error', true);
        }
        return $taskId;
    }
}
